package com.my.search.service.serviceImpl;

import com.my.model.common.dtos.ResponseResult;
import com.my.model.common.enums.AppHttpCodeEnum;
import com.my.model.user.pojos.ApUser;
import com.my.search.pojos.ApUserSearch;
import com.my.search.service.ApUserSearchService;
import com.my.utils.thread.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存搜索记录
     * @param keyWord
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyWord, Integer userId) {
        log.info("保存搜索历史...");
        //1.查询当前用户搜索关键词
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyWord));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query,ApUserSearch.class);

        //2.存在该关键词，更新时间
        if(apUserSearch != null) {
            log.info("关键词{}已存在，更新时间",keyWord);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //3.不存在关键词
        log.info("不存在该关键词");
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyWord);
        apUserSearch.setCreatedTime(new Date());

        Query query1 = Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));

        List<ApUserSearch> userSearchList = mongoTemplate.find(query1, ApUserSearch.class);
        //3.1搜索记录条数不大于10
        if(userSearchList == null || userSearchList.size() < 10) {
            log.info("搜索记录数不大于10，保存关键词{}",keyWord);
            mongoTemplate.save(apUserSearch);
        } else {
            //3.2搜索记录条数大于10
            //3.2.1获取时间最旧的数据
            ApUserSearch apUserSearch1 = userSearchList.get(userSearchList.size() - 1);
            log.info("关键词{}替换成{}",apUserSearch1.getKeyword(),keyWord);
            //3.2.2替换最后一条记录
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(apUserSearch1.getId())),apUserSearch);
        }

    }

    /**
     * 加载历史记录
     * @return
     */
    @Override
    public ResponseResult loadHistory() {
        log.info("加载用户历史搜索记录...");
        //1.获取当前用户id
        ApUser user = AppThreadLocalUtils.getUser();
        if(user != null) {
            Integer userId = user.getId();

            //2.查询该用户历史搜索记录
            Query query = Query.query(Criteria.where("userId").is(userId));
            query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
            List<ApUserSearch> searchList = mongoTemplate.find(query, ApUserSearch.class);

            //3.返回结果
            return ResponseResult.okResult(searchList);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
    }

    /**
     * 删除历史记录
     * @param map
     * @return
     */
    @Override
    public ResponseResult delHistory(Map map) {
        log.info("删除搜索记录...");
        if(map == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null) {
            //用户未登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取参数
        Integer userId = user.getId();
        String id = (String) map.get("id");
        //获取历史记录
        Query query = Query.query(Criteria.where("id").is(id).and("userId").is(userId));
        mongoTemplate.remove(query,ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
